package com.thinkgem.jeesite.modules.app.api;


import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.app.entity.*;

import com.thinkgem.jeesite.modules.app.service.CommunityService;
import com.thinkgem.jeesite.modules.app.service.PhoneMessageService;
import com.thinkgem.jeesite.modules.cms.entity.*;
import com.thinkgem.jeesite.modules.cms.service.*;
import com.thinkgem.jeesite.modules.oa.entity.OaNotify;
import com.thinkgem.jeesite.modules.oa.service.OaNotifyService;
import com.thinkgem.jeesite.modules.phone.entity.CommunityPhone;
import com.thinkgem.jeesite.modules.phone.service.CommunityPhoneService;
import com.thinkgem.jeesite.modules.pub.entity.AdMake;
import com.thinkgem.jeesite.modules.pub.entity.Myrelease;
import com.thinkgem.jeesite.modules.pub.entity.ScreenPoint;
import com.thinkgem.jeesite.modules.pub.service.AdMakeService;
import com.thinkgem.jeesite.modules.pub.service.MyreleaseService;
import com.thinkgem.jeesite.modules.pub.service.ScreenPointService;
import com.thinkgem.jeesite.modules.shop.entity.BusinessProduct;
import com.thinkgem.jeesite.modules.shop.service.BusinessCategoryService;
import com.thinkgem.jeesite.modules.shop.service.BusinessProductService;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm;
import com.thinkgem.jeesite.modules.sys.security.UsernamePasswordToken;
import com.thinkgem.jeesite.modules.sys.service.*;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;


import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.text.SimpleDateFormat;
import java.lang.reflect.AccessibleObject;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by xiaguoqiang on 16/5/12.
 */
@Controller
@RequestMapping(value = "${adminPath}/api/community")
public class CommunityApi extends BaseController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CommunityService communityService;

    @Autowired
    private DictService dictService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ClassifiedInfoService classifiedInfoService;

    @Autowired
    private ClassifiedInfoDataService classifiedInfoDataService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private OaNotifyService oaNotifyService;

    @Autowired
    private CmsBusinessService cmsBusinessService;

    @Autowired
    private BusinessRepairsService businessRepairsService;

    @Autowired
    private UserBusinessService userBusinessService;

    @Autowired
    private BusinessCategoryService businessCategoryService;

    @Autowired
    private BusinessProductService businessProductService;

    @Autowired
    private AdMakeService adMakeService;

    @Autowired
    private ScreenPointService screenPointService;

    @Autowired
    private CommunityPhoneService communityPhoneService;

    @Autowired
    private PhoneMessageService phoneMessageService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private HomePictureService homePictureService;

    @Autowired
    private MyreleaseService myreleaseService;

    // 文件保存目录相对路径
    private String basePath = "userfiles/1/images/photo/";
    private String basePathPhoto = "/ex_community/userfiles/1/images/photo/";

    private String base = "userfiles/";

    private String baseUrl = "/ex_community/userfiles/";

    private String basePaths = "/images/photo/";

    private String baseBusinessPaths = "/images/cms/cmsBusiness/";

    private Date date = new Date();
    private SimpleDateFormat matter1 = new SimpleDateFormat("yyyy");
    private SimpleDateFormat matter2 = new SimpleDateFormat("MM");


    @ResponseBody
    @RequestMapping(value = "getCategory")
    public Object getCategory(@RequestParam("pID") String pID,
                                  @RequestParam("callback") String callback ){
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Category> datas = categoryService.findCategoryByPID(pID);
        for(Category category : datas)
        {
            Map<String, Object> map = Maps.newHashMap();
            map.put("fID", category.getId());
            map.put("pID", category.getParent().getId());
            map.put("fTitle", category.getName());
            map.put("fImg",category.getImage());
            mapList.add(map);
        }
        return new JSONPObject(callback,mapList);
    }


    /**
     * 获取所有分类
     * @param callback
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getClassifiedCategorys")
    public Object getClassifiedInfos(@RequestParam("callback") String callback,Category c){
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Category> datas;
        if(StringUtils.isEmpty(c.getId()))
            datas = categoryService.findByParentId("11","1");
        else
            datas = categoryService.findByParentId(c.getId(),"1");
        for(Category category : datas)
        {
            Map<String, Object> map = Maps.newHashMap();
            map.put("fID", category.getId());
            map.put("pID", category.getParent().getId());
            map.put("fTitle", category.getName());
            map.put("fImg",category.getImage());
            mapList.add(map);
        }
        return new JSONPObject(callback,mapList);
    }

    /**
     * 获取掌中社区分类下的所有分类
     * @param callback
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getPalmCommunityCategorys")
    public Object getPalmCommunityCategorys(@RequestParam("callback") String callback){
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Category> datas;
        datas = categoryService.findByParentId("0987654321","1");
        for(Category category : datas)
        {
            Map<String, Object> map = Maps.newHashMap();
            map.put("fID", category.getId());
            map.put("pID", category.getParent().getId());
            map.put("fTitle", category.getName());
            map.put("fImg",category.getImage());
            mapList.add(map);
        }
        return new JSONPObject(callback,mapList);
    }


    /**
     * 获取新闻分类
     * @param callback
     * @param c
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getNewsCategorys")
    public Object getNewsCategorys(@RequestParam("callback") String callback,Category c){
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Category> datas;
        if(StringUtils.isEmpty(c.getId()))
            datas = categoryService.findByParentId("121","1");
        else
            datas = categoryService.findByParentId(c.getId(),"1");
        for(Category category : datas)
        {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", category.getId());
            map.put("title", category.getName());
            map.put("img",category.getImage());
            mapList.add(map);
        }
        return new JSONPObject(callback,mapList);
    }

    /**
     * 按分类信息的分类id获取分类信息
     * @param callback
     * @param classifiedInfo
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getClassInfosByCategoryId")
    public Object getClassinfoByCategoryId(@RequestParam("callback") String callback, ClassifiedInfo classifiedInfo, HttpServletRequest request, HttpServletResponse response){
        List<ApiClassfiedInfo> list = Lists.newArrayList();
        AppResultEntity result = new AppResultEntity();
        Page<ClassifiedInfo> page = classifiedInfoService.findPage(new Page<ClassifiedInfo>(request, response), classifiedInfo, true);
        for(ClassifiedInfo classInfo : page.getList())
        {
            ApiClassfiedInfo info = new ApiClassfiedInfo(classInfo);
            info.setContent(communityService.findClassContentById(info.getId()).getContent());
            list.add(info);
        }
        result.setData(list.size()>0 ? list : "");
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);
    }

    /**
     * 按分类信息的分类id获取分类信息
     * @param callback
     * @param classifiedInfo
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getSecondHand")
    public Object getSecondHand(@RequestParam("callback") String callback, ClassifiedInfo classifiedInfo, HttpServletRequest request, HttpServletResponse response){
        List<ApiClassfiedInfo> list = Lists.newArrayList();
        AppResultEntity result = new AppResultEntity();
        Page<ClassifiedInfo> page = classifiedInfoService.findPages(new Page<ClassifiedInfo>(request, response), classifiedInfo);
        for(ClassifiedInfo classInfo : page.getList())
        {
            ApiClassfiedInfo info = new ApiClassfiedInfo(classInfo);
            info.setContent(communityService.findClassContentById(info.getId()).getContent());
            list.add(info);
        }
        result.setData(list.size()>0 ? list : "");
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);
    }

    /**
     * 按照title搜索分类信息
     * @param callback
     * @param classifiedInfo
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "SearchClassInfo")
    public Object SearchClassInfo(@RequestParam("callback") String callback, ClassifiedInfo classifiedInfo, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        List<ApiClassfiedInfo> list = Lists.newArrayList();
        Page<ClassifiedInfo> page = classifiedInfoService.findPage(new Page<ClassifiedInfo>(request, response), classifiedInfo, true);
        for(ClassifiedInfo classInfo : page.getList())
        {
            ApiClassfiedInfo info = new ApiClassfiedInfo(classInfo);
            info.setContent(communityService.findClassContentById(info.getId()).getContent());
            list.add(info);
        }
        result.setData(list.size()>0 ? list : "");
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);
    }


    /**
     * 根据分类信息id获取分类详情
     * @param callback
     * @param classifiedInfo
     * @param request
     * @param response
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "getClassInfuById")
    public  Object getClassInfuById(@RequestParam("callback") String callback, ClassifiedInfo classifiedInfo, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        ApiClassfiedInfo info = new ApiClassfiedInfo(classifiedInfoService.get(classifiedInfo));
        info.setContent(communityService.findClassContentById(info.getId()).getContent());
        result.setData(info);
        return new JSONPObject(callback,result);
    }

    @ResponseBody
    @RequestMapping(value = "getBusinessBycategoryId")
    public Object getBusinessBycategoryId(@RequestParam("callback") String callback,CmsBusiness cmsBusiness, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        Page<CmsBusiness> page=cmsBusinessService.findPage(new Page<CmsBusiness>(request, response), cmsBusiness);
        result.setData(page.getList().size()>0 ? page.getList() : "");
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);
    }

    /**
     * 按新闻分类id获取新闻列表
     * @param callback
     * @param article
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getNewsByCategoryId")
    public Object getNewsByCategoryId(@RequestParam("callback") String callback, Article article, HttpServletRequest request, HttpServletResponse response){
        List<AArticle> list = Lists.newArrayList();
        AppResultEntity resultEntity = new AppResultEntity();
        Page<Article> page = articleService.findPage(new Page<Article>(request, response), article, false);
        for(Article item : page.getList())
        {
            AArticle info = new AArticle(item);
            info.setContent(communityService.findArticleContentById(info.getId()).getContent());
            list.add(info);
        }
        resultEntity.setData(list.size()>0 ? list : "");
        resultEntity.setPageSize(page.getPageSize());
        resultEntity.setPage(page.getPageNo());
        return new JSONPObject(callback,resultEntity);
    }

    /**
     * 获取首页滚动新闻列表
     * @param callback
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getNewsListByCategoryId")
    public Object getNewsListByCategoryId(@RequestParam("callback") String callback, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        List<AArticle> list = Lists.newArrayList();
        List<Article> aList = new ArrayList<Article>();
        Article articlehome = new Article();
        Category category = new Category();
        category.setId("90f11e024f214e5cb35b923ab42f5965");
        articlehome.setCategory(category);
        aList = articleService.findHomeNews(articlehome);
        for(Article article1 : aList){
            AArticle aArticle = new AArticle(article1);
            list.add(aArticle);
        }
        result.setData(list.size()>0 ? list : "");
        return new JSONPObject(callback,result);
    }


    /**
     * 根据新闻id获取新闻详情
     * @param callback
     * @param article
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getNewsById")
    public Object getNewsById(@RequestParam("callback") String callback, Article article, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        AArticle info = new AArticle(articleService.get(article));
        info.setContent(communityService.findArticleContentById(info.getId()).getContent());
        result.setData(info);
        return new JSONPObject(callback,result);
    }
    @ResponseBody
    @RequestMapping(value = "getCommunityInfo")
    public Object getCommunityInfo(@RequestParam("callback") String callback,String communityId){
        ACommunity community = new ACommunity();
        community.setMaster("夏国强");
        community.setAddress("新疆乌鲁木齐幸福路");
        community.setId(communityId);
        community.setEmail("love_mobile@163.com");
        community.setName("幸福社区");
        community.setCode("831100");
        community.setPhone("15699166930");
        community.setIntroduction("幸福社区来源于");
        return new JSONPObject(callback,community);
    }

    @ResponseBody
    @RequestMapping(value = "getNeighborhoodInfo")
    public Object getNeighborhoodInfo(@RequestParam("callback") String callback,String neighborhoodId){
        ACommunity community = new ACommunity();
        community.setMaster("夏国强");
        community.setAddress("新疆乌鲁木齐幸福路");
        community.setId(neighborhoodId);
        community.setEmail("love_mobile@163.com");
        community.setName("幸福社区");
        community.setCode("831100");
        community.setPhone("15699166930");
        community.setIntroduction("幸福小区来源于");
        return new JSONPObject(callback,community);
    }

    /**
     * 登陆接口  返回个人信息和小区信息、社区信息
     * @param callback
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "login")
    public Object login(@RequestParam("callback") String callback,HttpServletRequest request){
        String host = request.getRemoteHost();
        AppResultEntity result = new AppResultEntity();
        AuthenticationToken token = new UsernamePasswordToken(request.getParameter("username"), request.getParameter("password").toCharArray(), true, host
                ,"",true);
        try {
            Subject subject = SecurityUtils.getSubject();
            ThreadContext.bind(subject);
            if(subject.getPrincipal() != null){
                subject.logout();
            }
            subject.login(token);
            SystemAuthorizingRealm.Principal principal = (SystemAuthorizingRealm.Principal) subject.getPrincipal();
            Map<String,Object> map = new HashMap<String, Object>();

            User user = systemService.getUser(principal.getId());

            Office company = officeService.get(user.getCompany().getId());
            String sex = user.getSex();
            if(sex != null && !sex.equals("")) {
                user.setSex(user.getSex().equals("1") ? "男" : "女");
            }
            if(company.getType().equals("5")){
                map.put("user",new AUser(user));
                if(user.getOffice() != null && user.getOffice().getId() != null && !user.getOffice().getId().equals("")) {
                    map.put("office",new ACommunity(officeService.get(user.getOffice().getId())));
                }
                map.put("company",new ACommunity(company));
            }else {
                logger.info("该用户不能登录");
                result.setErrNo(-1);
                result.setErrMessage("该用户不能登录");
            }

            result.setData(map);
//            ACommunity community = new ACommunity(office);
//            AUser result = new AUser(user);
//            result.setCommunityId("1");
//            result.setNeighborhoodId("2");

        } catch (AuthenticationException e) {
            logger.info("验证失败");
            result.setErrNo(-1);
            result.setErrMessage("用户认证失败");
//            return null;
        } catch (Exception e) {
            logger.error("登录失败", e);
            result.setErrNo(-1);
            result.setErrMessage("用户登录失败");
//            return null;
        }
        return new JSONPObject(callback,result);
    }


    /**
     * 更换小区接口
     * @param callback
     * @param user
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "changeNeighborhood")
    public Object changeNeighborhood(@RequestParam("callback") String callback,User user,HttpServletRequest request){
        AppResultEntity result = new AppResultEntity();
        Office office = new Office();
        Office company = new Office();
        Map<String,Object> map = new HashMap<String, Object>();
        office = officeService.get(user.getOffice().getId());
        company = officeService.get(office.getParentId());
        user = systemService.getUser(user.getId());
        user.setOffice(office);
        user.setCompany(company);
        systemService.saveUser(user);
        map.put("user",new AUser(user));
        map.put("office",new ACommunity(office));
        map.put("company",new ACommunity(company));
        result.setData(map);
        return new JSONPObject(callback,result);
    }


    /**
     * 获取通告，传小区id或社区id
     * @param callback
     * @param request
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "getNotify")
    public Object getNotify(@RequestParam("callback") String callback,HttpServletRequest request){
        AppResultEntity result = new AppResultEntity();
        String officeId = request.getParameter("id");
//        String companyId = request.getParameter("companyId");
            String userId = officeService.get(officeId).getPrimaryPerson().getId();
            result.setData(oaNotifyService.getNotifyByCreateId(userId));
        return new JSONPObject(callback,result);
    }

    /**
     * 获取社区通告
     * @param callback
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getNotifyNew")
    public Object getNotifyNew(@RequestParam("callback") String callback,OaNotify oaNotify,HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        Page<OaNotify> page=oaNotifyService.findPage(new Page<OaNotify>(request, response), oaNotify);
        result.setData(page.getList());
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);
    }


    /**
     * 获取所有小区
     * 可以按照小区名字搜索
     * @param callback
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAllNeighborhood")
    public Object getAllNeighborhood(@RequestParam("callback") String callback,Office office,HttpServletRequest request){
        AppResultEntity result = new AppResultEntity();
        List<ANeighborhood> list = communityService.getAllNeighborhood(office);
        if(null != list && list.size() != 0) {
            result.setData(list);
        }else {
            result.setData("");
        }
        return new JSONPObject(callback,result);
    }

    /**
     * 获取所有社区
     * @param callback
     * @param office
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAllCommunity")
    public Object getAllCommunity(@RequestParam("callback") String callback,Office office,HttpServletRequest request){
        AppResultEntity result = new AppResultEntity();
        List<Office> list = communityService.getAllCommunity(office);
        if(null != list && list.size() != 0) {
            result.setData(list);
        }else {
            result.setData("");
        }
        return new JSONPObject(callback,result);
    }

    /**
     * 更换头像
     * @param user
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updatePhoto")
    public Object updatePhoto(User user,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        response.setHeader("Access-Control-Allow-Origin", "*");
//        User user = new User();
        Map<String,Object> map = new HashMap<String, Object>();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> names =  multipartRequest.getFileNames();
        String path = request.getRealPath("/") + base + user.getId() + basePaths + matter1.format(date) + "/" + matter2.format(date) + "/";
        System.out.print(path);

        String url = "";
        while (names.hasNext()) {
            String s = UUID.randomUUID().toString();
            s =  s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
            String name = names.next();
            MultipartFile file = multipartRequest.getFile(name);
            File saveFile = new File(path,s + ".png");
            File pathFile = new File(path);
            if(!pathFile.exists()){
                pathFile.mkdirs();
            }
            url = baseUrl + user.getId() + basePaths + matter1.format(date) + "/" + matter2.format(date) + "/" + s +  ".png";
            try {
                file.transferTo(saveFile);
//                urls += (url + ",");
            } catch (IOException e) {
                e.printStackTrace();
                result.setErrNo(-1);
                result.setErrMessage(e.getMessage());
            }
        }

        user = systemService.getUser(user.getId());
        if(url.length()>0) {
            user.setPhoto(url);
        }
        user.setUpdateBy(user);
        user.setUpdateDate(new Date());
        systemService.updateUserInfo(user);
        user = systemService.getUser(user.getId());
        map.put("user",new AUser(user));
        if(user.getOffice() != null ){
            map.put("office",new ACommunity(officeService.get(user.getOffice().getId())));
        }
        map.put("company",new ACommunity(officeService.get(user.getCompany().getId())));
        result.setData(map);
        return result;

    }

    /**
     * 注册
//     * @param callback
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "register")
    public Object register(User user,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        response.setHeader("Access-Control-Allow-Origin", "*");
//        User user = new User();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> names =  multipartRequest.getFileNames();
        String path = request.getRealPath("/") + basePath + matter1.format(date) + "/" + matter2.format(date) + "/";
        System.out.print(path);
//
        String url = "";
        while (names.hasNext()) {
            String s = UUID.randomUUID().toString();
            s =  s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
            String name = names.next();
            MultipartFile file = multipartRequest.getFile(name);
            File saveFile = new File(path,s + ".png");
            File pathFile = new File(path);
            if(!pathFile.exists()){
                pathFile.mkdir();
            }
            url = basePathPhoto  + matter1.format(date) + "/" + matter2.format(date) + "/" + s +  ".png";
            try {
                file.transferTo(saveFile);
//                urls += (url + ",");
            } catch (IOException e) {
                e.printStackTrace();
                result.setErrNo(-1);
                result.setErrMessage(e.getMessage());
            }
        }
        if(url.length()>0) {
//            String dataUrl = urls.substring(0, urls.length() - 1);
//            data.setDataUrl(url);
            user.setPhoto(url);
        }

        Role role = new Role();
        List<Role> roleLists = new ArrayList<Role>();
//        user.setCompany(new Office(officeService.get(user.getOffice().getId()).getParentId()));
        user.setNewPassword(user.getPassword());
        user.setUserType("3");
        role.setId("5");
        roleLists.add(role);
        user.setRoleList(roleLists);
        user.setUserType("3");
        // 如果新密码为空，则不更换密码
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
        }
        if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
            result.setErrNo(-1);
            result.setErrMessage("用户名已存在");
            return result;
        }

        // 保存用户信息
        systemService.saveUser(user);
        // 清除当前用户缓存
        if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
            UserUtils.clearCache();
            //UserUtils.getCacheMap().clear();
        }
        if((user.getCompany().getId() == null || user.getCompany().getId().equals("")) || (user.getLoginName() == null || user.getLoginName().equals("")) || (user.getPassword() == null || user.getPassword() .equals("")) ||
                (user.getName() == null || user.getName().equals(""))){
            result.setErrNo(-1);
            result.setErrMessage("账号、密码不能为空");
//            return new JSONPObject(callback,result);
            return result;
        }
        if((user.getOpenId() != null && !user.getOpenId().equals("")) || (user.getQqId() != null && !user.getQqId().equals("")) || (user.getSinaId() != null && !user.getSinaId().equals(""))){
            Map<String,Object> map = new HashMap<String, Object>();
            Office office = officeService.get(user.getOffice().getId());
            ACommunity aCommunity = new ACommunity(office);
            String sex = user.getSex();
            if(sex != null && !sex.equals("")) {
                user.setSex(user.getSex().equals("1") ? "男" : "女");
            }
            if(office.getType().equals("5")){
                map.put("user",new AUser(user));
                if(user.getOffice() != null && user.getOffice().getId() != null && !user.getOffice().getId().equals("")) {
                    map.put("office",new ACommunity(officeService.get(user.getOffice().getId())));
                }
                map.put("company",new ACommunity(officeService.get(user.getCompany().getId())));
//                return ;
            }
            result.setData(map);
        }
//        return new JSONPObject(callback,result);
        return result;
    }

    /**
     * 商户注册
     * @param user
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "businessReg")
    public Object businessReg(User user,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        response.setHeader("Access-Control-Allow-Origin", "*");
//        User user = new User();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> names =  multipartRequest.getFileNames();
        String path = request.getRealPath("/") + basePath + matter1.format(date) + "/" + matter2.format(date) + "/";
        System.out.print(path);
//
        String url = "";
        while (names.hasNext()) {
            String s = UUID.randomUUID().toString();
            s =  s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
            String name = names.next();
            MultipartFile file = multipartRequest.getFile(name);
            File saveFile = new File(path,s + ".png");
            File pathFile = new File(path);
            if(!pathFile.exists()){
                pathFile.mkdir();
            }
            url = basePathPhoto  + matter1.format(date) + "/" + matter2.format(date) + "/" + s +  ".png";
            try {
                file.transferTo(saveFile);
//                urls += (url + ",");
            } catch (IOException e) {
                e.printStackTrace();
                result.setErrNo(-1);
                result.setErrMessage(e.getMessage());
            }
        }
        if(url.length()>0) {
//            String dataUrl = urls.substring(0, urls.length() - 1);
//            data.setDataUrl(url);
            user.setPhoto(url);
        }

        Role role = new Role();
        List<Role> roleLists = new ArrayList<Role>();
//        String id = officeService.get(user.getOffice().getId()).getParentId();
//        user.setCompany(new Office(id));
//        user.setCompany(new Office(officeService.get(user.getOffice().getId()).getParentId()));
        user.setNewPassword(user.getPassword());
//        user.setUserType("3");
        role.setId("971b0fd9688c43a0ac77292655b173d4");
        roleLists.add(role);
        user.setRoleList(roleLists);
        user.setUserType("4");
        // 如果新密码为空，则不更换密码
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
        }
        if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
            result.setErrNo(-1);
            result.setErrMessage("用户名已存在");
            return result;
        }

        // 保存用户信息
        systemService.saveUser(user);
        // 清除当前用户缓存
        if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
            UserUtils.clearCache();
            //UserUtils.getCacheMap().clear();
        }
        if((user.getCompany().getId() == null || user.getCompany().getId().equals("")) || (user.getLoginName() == null || user.getLoginName().equals("")) || (user.getPassword() == null || user.getPassword() .equals("")) ||
                (user.getName() == null || user.getName().equals(""))){
            result.setErrNo(-1);
            result.setErrMessage("账号、密码不能为空");
//            return new JSONPObject(callback,result);
            return result;
        }
        if((user.getOpenId() != null && !user.getOpenId().equals("")) || (user.getQqId() != null && !user.getQqId().equals("")) || (user.getSinaId() != null && !user.getSinaId().equals(""))){
            Map<String,Object> map = new HashMap<String, Object>();
            user = systemService.findUserByOpenId(user);
//            Office office = officeService.get(user.getOffice().getId());
//            ACommunity aCommunity = new ACommunity(office);
            String sex = user.getSex();
            if(sex != null && !sex.equals("")) {
                user.setSex(user.getSex().equals("1") ? "男" : "女");
            }
            if(user.getCompany().getType().equals("5")){
                map.put("user",new AUser(user));
                if(user.getOffice() != null && user.getOffice().getId() != null && !user.getOffice().getId().equals("")) {
                    map.put("office",new ACommunity(officeService.get(user.getOffice().getId())));
                }
                map.put("company",new ACommunity(officeService.get(user.getCompany().getId())));
//                return ;
            }
            result.setData(map);
        }
//        return new JSONPObject(callback,result);
        return result;
    }
    /**
     * 根据openId查询用户是否绑定活存在
     * @param callback
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectOpenId")
    Object selectOpenId(@RequestParam("callback") String callback,User user){
        AppResultEntity result = new AppResultEntity();
//        User user = new User();
        List<Object> list = new ArrayList<Object>();
        user = systemService.findUserByOpenId(user);
        if(user != null && !user.getLoginName().equals("") && !user.getPassword().equals("")){
            AUser aUser = new AUser(user);
            result.setErrNo(1);
            result.setErrMessage("此用户已绑定");
            Office office = officeService.get(user.getOffice().getId());
            ACommunity aCommunity = new ACommunity(office);
            String sex = user.getSex();
            if(sex != null && !sex.equals("")) {
                user.setSex(user.getSex().equals("1") ? "男" : "女");
            }
            if(office.getType().equals("6")){
                list.add(new AUser(user));
                list.add(aCommunity);
                list.add(new ACommunity(officeService.get(user.getOffice().getParentId())));
//                return ;
            }
            result.setData(list);
        }else{
            result.setErrMessage("此用户未绑定");
            result.setErrNo(2);
        }
        return new JSONPObject(callback,result);
    }

    /**
     * 已有账号绑定openId
     * @param callback
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "alreadyAccountBind")
    Object alreadyAccountBind(@RequestParam("callback") String callback,User user){
        AppResultEntity result = new AppResultEntity();
        List<Object> list = new ArrayList<Object>();
        if(!user.getLoginName().equals("") && user.getLoginName() != null && !user.getPassword().equals("") &&
                user.getPassword() != null){
            systemService.alreadyAccountBind(user);
            result.setErrNo(1);
            result.setErrMessage("绑定成功");
            user = systemService.findUserByOpenId(user);
            Office office = officeService.get(user.getOffice().getId());
            ACommunity aCommunity = new ACommunity(office);
            String sex = user.getSex();
            if(sex != null && !sex.equals("")) {
                user.setSex(user.getSex().equals("1") ? "男" : "女");
            }
            if(office.getType().equals("6")){
                list.add(new AUser(user));
                list.add(aCommunity);
                list.add(new ACommunity(officeService.get(user.getOffice().getParentId())));
//                return ;
            }
            result.setData(list);
        }else{
            result.setErrNo(-1);
            result.setErrMessage("绑定失败");
        }

        return new JSONPObject(callback,result);
    }
    /**
     * 周边商家
     * @param callback
     * @param user
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "roundBusiness")
    public Object getRoundBusiness(@RequestParam("callback") String callback,User user,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        user.setUserType("4");
        Page<User> page=systemService.findPage(new Page<User>(request, response), user);

//        List<User> list = new ArrayList<User>( systemService.findUserByOfficeIdAndUserType(user));
        result.setData(page.getList().size() > 0 ? page.getList() : "");
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);


    }

    /**
     * 报修接口
     * @param callback
     * @param businessRepairs
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "repairs")
    public Object repairs(@RequestParam("callback") String callback,BusinessRepairs businessRepairs,HttpServletRequest request){
        AppResultEntity result = new AppResultEntity();
//        SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
//        Category category = new Category();
//        category.setId("999999");
//        businessRepairs.setCategory(category);
//        businessRepairs.setId(principal.getId());
        if(businessRepairs.getMobile() == null || businessRepairs.getMobile().equals("") || businessRepairs.getOffice().getId() == null || businessRepairs.getOffice().getId().equals("")){
            result.setErrNo(-1);
            result.setErrMessage("电话号码不能为空！！！");
            return new JSONPObject(callback,result);
        }
        businessRepairsService.save(businessRepairs);
        return new JSONPObject(callback,result);
    }

    /**
     * 品牌特惠接口
     * @param callback
     * @param cmsBusiness
     * @param request
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "brandPreference")
    public Object brandPreference(@RequestParam("callback") String callback,CmsBusiness cmsBusiness,HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        Page<CmsBusiness> page = cmsBusinessService.findPage(new Page<CmsBusiness>(request, response), cmsBusiness);
        result.setData(page.getList().size() > 0 ? page.getList() : "");
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "modifyPwd")
    public Object modifyPwd(@RequestParam("callback") String callback,String oldPassword, String newPassword,String id) {
//        User user = UserUtils.getUser();
        User user = systemService.getUser(id);
        AppResultEntity result = new AppResultEntity();
        if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
            if (SystemService.validatePassword(oldPassword, user.getPassword())){
                systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
            }else{
                result.setErrNo(-1);
                result.setErrMessage("修改密码失败，旧密码错误");
            }
        }
        return new JSONPObject(callback,result);
    }

    /**
     * 重置密码
     * @param callback
     * @param newPassword
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "resetPwd")
    public Object resetPwd(@RequestParam("callback") String callback, String newPassword,String loginName) {
        AppResultEntity result = new AppResultEntity();
        User user = systemService.getUserByLoginName(loginName);
        if(user != null){
            systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
        }else {
            result.setErrNo(-1);
            result.setErrMessage("无此账号!!!");
        }

        return new JSONPObject(callback,result);
    }

    /**
     * 修改个人信息
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "modifyMobileInfo")
    public Object modifyInfo(@RequestParam("callback") String callback,User user){
        AppResultEntity result = new AppResultEntity();
        communityService.updateMobileInfo(user);
        return new JSONPObject(callback,result);
    }

    /**
     * 获取三大商城
     * @param callback
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getMall")
    public Object getMall(@RequestParam("callback") String callback,HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        Dict dict = new Dict();
        dict.setType("business_type");
        List<ADict> AdictList = new ArrayList<ADict>();
        List<Dict> list = dictService.findList(dict);
        for(Dict dict1 : list){
            ADict aDict = new ADict(dict1);
            AdictList.add(aDict);
        }
        result.setData(AdictList);
        return new JSONPObject(callback,result);
    }

    /**
     * 按照商城获取商城店家
     * @param callback
     * @param userBusiness
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getBusiness")
    public Object getBusiness(@RequestParam("callback") String callback,UserBusiness userBusiness,HttpServletRequest request,HttpServletResponse response){
       AppResultEntity result = new AppResultEntity();
        Page<UserBusiness> page = userBusinessService.findPage(new Page<UserBusiness>(request, response), userBusiness);
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        result.setData(page.getList().size() > 0 ? page.getList() : "");
        return new JSONPObject(callback,result);
    }

    /**
     * 获取商品所有分类
     * @param callback
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getProductCategory")
    public Object getProductCategory(@RequestParam("callback") String callback,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        result.setData(businessCategoryService.findByParentId("2"));
        return new JSONPObject(callback,result);
    }

    /**
     * 根据分类id获取商品列表
     * @param callback
     * @param businessProduct
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getProductByCategoryId")
    public Object getProductCategory(@RequestParam("callback") String callback,BusinessProduct businessProduct,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
//        User user = new User();
//        user.setId("");
//        businessProduct.setBusiness(user);
        Page<BusinessProduct> page = businessProductService.findPage(new Page<BusinessProduct>(request, response), businessProduct);
        result.setPageSize(page.getPageSize());
        result.setPage(page.getPageNo());
        result.setData(page.getList().size() > 0 ? page.getList() : "");
        return new JSONPObject(callback,result);
    }

    /**
     * 商家商城获取菜店商品信息列表
     * @param callback
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getVegetable")
    public Object getVegetable(@RequestParam("callback") String callback,CmsBusiness cmsBusiness, HttpServletResponse response, HttpServletRequest request){
        AppResultEntity result = new AppResultEntity();
//        Category category = new Category();
//        CmsBusiness cmsBusiness = new CmsBusiness();
//        User user = new User();
//        user.setId("");
//        category.setId("");
//        cmsBusiness.setUser(user);
//        cmsBusiness.setCategory(category);

        Page<CmsBusiness> page=cmsBusinessService.findPage(new Page<CmsBusiness>(request, response), cmsBusiness);
        result.setData(page.getList().size()>0 ? page.getList() : "");
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);
    }

    /**
     * 获取全部大屏广告点位,广告播放时长和播放周期
     * @param callback
     * @param screenPoint
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAdPoint")
    public Object getAdPoint(@RequestParam("callback") String callback,ScreenPoint screenPoint,HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        List<Object> list = new ArrayList<Object>();
        List<Dict> adTimeList = new ArrayList<Dict>();
        List<Dict> adCycleList = new ArrayList<Dict>();
        List<ADict> aDictTimeList = new ArrayList<ADict>();
        List<ADict> aDictCycleList = new ArrayList<ADict>();
        Dict adTime = new Dict();
        Dict adCycle = new Dict();
        adTime.setType("ad_time");
        adCycle.setType("ad_cycle");
        adTimeList = dictService.findList(adTime);
        for(Dict dict:adTimeList){
            ADict aDict = new ADict(dict);
            aDictTimeList.add(aDict);
        }
        adCycleList = dictService.findList(adCycle);
        for(Dict dict:adCycleList){
            ADict aDict = new ADict(dict);
            aDictCycleList.add(aDict);
        }
        list.add(screenPointService.findList(screenPoint));
        list.add(aDictTimeList);
        list.add(aDictCycleList);
        result.setData(list);
        return new JSONPObject(callback,result);
    }

    /**
     * 客户端大屏广告定制信息插入后台
     * @param adMake
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "adRecord")
    public Object adRecord(AdMake adMake,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        response.setHeader("Access-Control-Allow-Origin", "*");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> names =  multipartRequest.getFileNames();
        String path = request.getRealPath("/") + base + adMake.getUser().getId() + basePaths + matter1.format(date) + "/" + matter2.format(date) + "/";
        String urls = "";
        adMake.setDelFlag("2");
        while (names.hasNext()) {
            String s = UUID.randomUUID().toString();
            s =  s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
            String name = names.next();
            MultipartFile file = multipartRequest.getFile(name);
            File saveFile = new File(path,s + ".png");
            File pathFile = new File(path);
            if(!pathFile.exists()){
                pathFile.mkdirs();
            }
            String url = baseUrl + adMake.getUser().getId() + basePaths + matter1.format(date) + "/" + matter2.format(date) + "/" + s +  ".png";
            try {
                file.transferTo(saveFile);
                urls += (url + "|");
            } catch (IOException e) {
                e.printStackTrace();
                result.setErrNo(-1);
                result.setErrMessage(e.getMessage());
            }
        }
        if(urls.length()>0) {
//            String dataUrl = urls.substring(0, urls.length() - 1);
//            data.setDataUrl(url);
            adMake.setImages(urls);
        }
        adMakeService.save(adMake);
        return result;
    }


    /**
     * 我要发布
     * @param myrelease
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "myRelease")
    public Object goToPublish(Myrelease myrelease, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        response.setHeader("Access-Control-Allow-Origin", "*");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> names =  multipartRequest.getFileNames();
        String path = request.getRealPath("/") + base + myrelease.getUserId() + basePaths + matter1.format(date) + "/" + matter2.format(date) + "/";
        String urls = "";
        myrelease.setDelFlag("2");
        while (names.hasNext()) {
            String s = UUID.randomUUID().toString();
            s =  s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
            String name = names.next();
            MultipartFile file = multipartRequest.getFile(name);
            File saveFile = new File(path,s + ".png");
            File pathFile = new File(path);
            if(!pathFile.exists()){
                pathFile.mkdirs();
            }
            String url = baseUrl + myrelease.getUserId() + basePaths + matter1.format(date) + "/" + matter2.format(date) + "/" + s +  ".png";
            try {
                file.transferTo(saveFile);
                urls += (url + "|");
            } catch (IOException e) {
                e.printStackTrace();
                result.setErrNo(-1);
                result.setErrMessage(e.getMessage());
            }
        }
        if(urls.length()>0) {
//            String dataUrl = urls.substring(0, urls.length() - 1);
//            data.setDataUrl(url);
            myrelease.setImages(urls);
        }
        myreleaseService.save(myrelease);
        return result;
    }


    /**
     * 获取便民电话
     * @param communityPhone
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getPhone")
    public Object getPhone(@RequestParam("callback") String callback,CommunityPhone communityPhone,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        Page<CommunityPhone> page = communityPhoneService.findPage(new Page<CommunityPhone>(request, response), communityPhone);
        result.setData(page.getList().size()>0 ? page.getList() : "");
        result.setPageSize(page.getPageSize());
        result.setPage(page.getPageNo());
        return new JSONPObject(callback,result);
    }

    /**
     * 发送短信和验证码验证
     * @param callback
     * @param phoneMessage
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sendMessage")
    public Object sendMessage(@RequestParam("callback") String callback, PhoneMessage phoneMessage){
        AppResultEntity result = new AppResultEntity();
        if(phoneMessage.getCode() == null || phoneMessage.getCode().equals("")){
            SendMessage api = new SendMessage();
            int i = (int)((Math.random()*9+1)*100000);
            phoneMessage.setCode(String.valueOf(i));
            String httpResponse =  api.testSend(phoneMessage);
            try {
                JSONObject jsonObj = new JSONObject( httpResponse );
                int error_code = jsonObj.getInt("error");
                String error_msg = jsonObj.getString("msg");
                if(error_code==0){
                    if(phoneMessageService.get(phoneMessage) == null) {
                        phoneMessageService.addCode(phoneMessage);
                    }else{
                        phoneMessageService.delete(phoneMessage);
                        phoneMessageService.addCode(phoneMessage);
                    }
                    System.out.println("Send message success.");
                }else{
                    System.out.println("Send message failed,code is "+error_code+",msg is "+error_msg);
                }
                result.setErrNo(error_code);
                result.setErrMessage(error_msg);
            } catch (JSONException ex) {
                Logger.getLogger(SendMessage.class.getName()).log(Level.SEVERE, null, ex);
//                return -1;
            }
        }else {
            if(phoneMessageService.get(phoneMessage).getCode().equals(phoneMessage.getCode())) {
                phoneMessageService.delete(phoneMessage);
            }else{
                result.setErrNo(-1);
                result.setErrMessage("验证码不正确");
            }
        }
        return new JSONPObject(callback,result);
    }

    /**
     * 商户上传店铺图片和介绍
     * @param userBusiness
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "businessPic")
    public Object businessPic(UserBusiness userBusiness,String originalImg,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        response.setHeader("Access-Control-Allow-Origin", "*");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> names =  multipartRequest.getFileNames();
        String path = request.getRealPath("/") + base + userBusiness.getId() + baseBusinessPaths + matter1.format(date) + "/" + matter2.format(date) + "/";
        String urls = "";
        while (names.hasNext()) {
            String s = UUID.randomUUID().toString();
            s =  s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
            String name = names.next();
            MultipartFile file = multipartRequest.getFile(name);
            File pathFile = new File(path);
            if(!pathFile.exists()){
                pathFile.mkdirs();

            }
            File saveFile = new File(path,s + ".png");
            String url = baseUrl + userBusiness.getId() + baseBusinessPaths + matter1.format(date) + "/" + matter2.format(date) + "/" + s +  ".png";
            try {
                file.transferTo(saveFile);
                urls += ("|" + url);
            } catch (IOException e) {
                e.printStackTrace();
                result.setErrNo(-1);
                result.setErrMessage(e.getMessage());
            }
        }
//        if(urls.length()>0) {
//            String dataUrl = urls.substring(0, urls.length() - 1);
//            data.setDataUrl(url);
            if(originalImg != null && originalImg != "") {
                originalImg = originalImg.replace(",", "|");
                userBusiness.setImages(urls + "|" + originalImg);
            }else{
                userBusiness.setImages(urls);
            }
//        }
        if (userBusiness.getIntroduce()!=null){
            userBusiness.setIntroduce(StringEscapeUtils.unescapeHtml4(
                    userBusiness.getIntroduce()));
        }
        userBusinessService.save(userBusiness);
        result.setData(userBusinessService.get(userBusiness.getId()));
        return result;
    }

    /**
     * 社区地图按id获取
     * @param request
     * @param response
     * @param area
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "officeMap")
    public Object officeMap(@RequestParam("callback") String callback,HttpServletRequest request,HttpServletResponse response,Area area){
        AppResultEntity result = new AppResultEntity();
        result.setData(areaService.findMapById(area));
        return new JSONPObject(callback,result);
    }

    /**
     * 根据街道id获取社区
     * @param callback
     * @param request
     * @param response
     * @param office
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "findOfficeByAreaId")
    public Object findOfficeByAreaId(@RequestParam("callback") String callback,HttpServletRequest request,HttpServletResponse response,Office office){
        AppResultEntity result = new AppResultEntity();

        Page<Office> page = officeService.findPages(new Page<Office>(request, response), office);
        result.setData(page.getList().size() > 0 ? page.getList() : "");
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return new JSONPObject(callback,result);
    }

    /**
     * 根据社区id获取此社区下的所有小区
     * @param callback
     * @param request
     * @param response
     * @param office
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "findChildById")
    public Object findChildById(@RequestParam("callback") String callback,HttpServletRequest request,HttpServletResponse response,Office office){
        AppResultEntity result = new AppResultEntity();
        result.setData(officeService.findChildById(office));
        return new JSONPObject(callback,result);
    }


    /**
     * 获取首页滚动图片
     * @param callback
     * @param request
     * @param response
     * @param homePicture
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getHomePicture")
    public Object getHomePicture(@RequestParam("callback") String callback,HttpServletRequest request,HttpServletResponse response,HomePicture homePicture){
        AppResultEntity result = new AppResultEntity();
        Page<HomePicture> page = homePictureService.findPage(new Page<HomePicture>(request, response), homePicture);
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        result.setData(page.getList().get(0));
        return new JSONPObject(callback,result);
    }

    /**
     * 获取首页资讯汇总
     * @param callback
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getHomeInformation")
    public Object getHomeInformation(@RequestParam("callback") String callback,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        List<ClassifiedInfo> classifiedInfoList = new ArrayList<ClassifiedInfo>();
        List<Category> list = categoryService.findByParentId("999999","1");
        for(Category category:list){
            List<ClassifiedInfo> listTem = classifiedInfoService.findByCategoryId(category.getId());
            if(null != listTem && !listTem.isEmpty()){
                for(ClassifiedInfo classifiedInfo:listTem){
                    classifiedInfo.setClassifiedInfoData(classifiedInfoDataService.get(classifiedInfo.getId()));
                    classifiedInfoList.add(classifiedInfo);
                }
            }
//            for(ClassifiedInfo classifiedInfo:classifiedInfoList){
//
//            }
        }
        result.setData(classifiedInfoList);
        return new JSONPObject(callback,result);
    }

    /**
     * 通过资讯id获取资讯详情
     * @param callback
     * @param request
     * @param response
     * @param classifiedInfo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getHomeInformationDetailById")
    public Object getHomeInformationDetailById(@RequestParam("callback") String callback,HttpServletRequest request,HttpServletResponse response,ClassifiedInfo classifiedInfo){
        AppResultEntity result = new AppResultEntity();
        classifiedInfo = classifiedInfoService.get(classifiedInfo.getId());
        ClassifiedInfoData classifiedInfoData = classifiedInfoDataService.get(classifiedInfo.getId());
        classifiedInfo.setClassifiedInfoData(classifiedInfoData);
        result.setData(classifiedInfo);
        return new JSONPObject(callback,result);
    }

    @ResponseBody
    @RequestMapping(value = "test")
    public Object test(HttpServletRequest request,HttpServletResponse response){
        String a="test";
        AppResultEntity result = new AppResultEntity();
        result.setData(a);
        response.setHeader("Access-Control-Allow-Origin", "*");
        return result;
    }
    public String checkLoginName(String oldLoginName, String loginName) {
        if (loginName !=null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
    }

//    public void main()
}
